import { createRouter, createWebHashHistory } from 'vue-router';
import { useUserStore } from '@/pinia/modules/user';
import { useRouterStore } from '@/admin/pinia/router';
import { useNProgress } from '@/utils/progress';
import tool from "@/utils/tool";

const { start, done } = useNProgress();
const routes = [{
  name: 'notfound',
  path: '/:pathMatch(.*)',
  text: '访问地址不存在',
  meta: {
    title: '访问地址不存在',
  },
  component: () => import('@/error/404.vue')
}];

const router = createRouter({
  history: createWebHashHistory(import.meta.env.VITE_WEB_PATH || '/'),
  routes
});

let isInitRouter = false;

const initRouter = async(userStore) => {
  await userStore.initUserInfo();
  const routerStore = useRouterStore();
  await routerStore.initRouter(router);
};

const handleKeepAlive = async(to) => {
  if (to.matched.some(item => item.meta.keepAlive)) {
    if (to.matched && to.matched.length > 2) {
      for (let i = 1; i < to.matched.length; i++) {
        const element = to.matched[i - 1]
        if (element.name === 'layout') {
          to.matched.splice(i, 1)
          await handleKeepAlive(to)
        }
        if (typeof element.components.default === 'function') {
          await element.components.default()
          await handleKeepAlive(to)
        }
      }
    }
  }
};

router.beforeEach(async(to) => {
  start();
  const userStore = useUserStore();
  to.meta.matched = [...to.matched];
  await handleKeepAlive(to);

  if (userStore.getToken()) {
    if (!isInitRouter) {
      isInitRouter = true;
      await initRouter(userStore);
      if (userStore.getToken()) {
        if (to.path === '/') {
          const routerStore = useRouterStore();
          const route = routerStore.getShowRoute();
          return { name: route ? route.name : 'notfound' };
        } else {
          await router.push({path: to.path});
        }
      } else {
        window.location.href = tool.getBaseUrl() + '/';
        return true;
      }
    } else {
      if (to.matched.length) {
        return true;
      } else {
        return { name: 'notfound' };
      }
    }
  } else {
    window.location.href = tool.getBaseUrl() + '/';
    return true;
  }
});

router.afterEach(() => {
  done();
});

router.onError(() => {
  done();
});

export default router;
